package com.thingple.web.bridge.settings;

import android.content.Context;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.thingple.h5.bridge.AbstractJsBridge;
import com.thingple.h5.bridge.BridgeConfig;
import com.thingple.h5.bridge.JsInvokeHandler;
import com.thingple.settings.AppConst;
import com.thingple.shared_context.SharedContext;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置文件
 * Created by lism on 2017/8/18.
 */
@BridgeConfig(moduleName = "settings")
public class SettingsJsBridgeImpl extends AbstractJsBridge implements SettingsJsBridge {
    public SettingsJsBridgeImpl(WebView webView, Context context) {
        super(webView, context);
    }

    @Override
    public void destroy() {

    }

    @JavascriptInterface
    @Override
    public void setting() {
        Map<String, String> params = new HashMap<>();
        SharedContext sharedContext = SharedContext.shareInstance();

        String broker = sharedContext.get(AppConst.BROKER_URL, null);// mqtt broker
        if (broker != null) {
            params.put("broker", broker);
        }

        String clientId = sharedContext.get(AppConst.CLIENT_ID, null);// mqtt client
        if (clientId != null) {
            params.put("clientId", clientId);
        }

        String api = sharedContext.get(AppConst.API, null);// api prefix
        if (api != null) {
            params.put("api", api);
        }

        JsInvokeHandler jsInvokeHandler = new JsInvokeHandler(getWebView());
        String module = moduleName() + "_listener";
        String function = "onSettings";
        jsInvokeHandler.module(module)
                .function(function)
                .params(params)
                .invoke();
    }

    @JavascriptInterface
    @Override
    public String get(String key) {
        if (key == null) {
            return null;
        }
        SharedContext sharedContext = SharedContext.shareInstance();
        return sharedContext.get(key, null);
    }

    @JavascriptInterface
    @Override
    public void save(String key, String value) {
        if (key != null && value != null) {
            SharedContext sharedContext = SharedContext.shareInstance();
            sharedContext.set(key, value);
        }
    }

    @JavascriptInterface
    @Override
    public void remove(String key) {
        if (key != null) {
            SharedContext sharedContext = SharedContext.shareInstance();
            sharedContext.set(key, "");
        }
    }

}
